from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework import status

from .models import Message
from .serializers import MessageModelSerializer


class MessageView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]  # 认证：采用Authorization方式认证JWT
    permission_classes = [IsAuthenticated]  # 权限指定：所有登录用户

    ''' 留言 '''
    def get(self, request):
        # 获取当前登录用户
        user = request.user
        # 获取用户所有留言信息
        messages = Message.objects.filter(user=user.id).all()
        serializer = MessageModelSerializer(instance=messages, many=True)

        return Response(serializer.data)

    def post(self, request):
        # 获取当前登录用户
        user = request.user
        # 获取留言信息
        message = request.data.get('message')
        # 构建反序列化字段
        data = {
            'user': user.id,
            'user_message': message
        }
        # 实例化序列化器对象
        serializer = MessageModelSerializer(data=data)
        # 校验 入库
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # 获取用户所有留言信息
        messages = Message.objects.filter(user=user.id).all()
        serializer_ = MessageModelSerializer(instance=messages, many=True)
        return Response(serializer_.data, status=status.HTTP_201_CREATED)
